<?php
declare (strict_types = 1);

namespace app\admin\middleware;


use app\common\service\TokenService;

class TokenCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        if(!in_array($request->controller(),config('admin.no_need_login'))){
            $token = $request->header("Authorization");
            if ($token && strpos($token, 'Bearer ') !== false) {
                $token = str_replace("Bearer ", '', $token);
                $tokenService = new TokenService();
                $user_id = $tokenService->verify($token);
                if(!$user_id){
                    return error("token已过期",[],401);
                }
                $request->user_id = $user_id;
            } else {
                return error("token不能为空");
            }
        }
        return $next($request);
    }
}
